<template>
  <div class="page-leveladd">
    <pk-dialog :title="title" @confirm="confirm" @onClose="onClose" :loading="loading">
      <div class="mt-12 mb-12">
        <pk-form :formConfig="formConfig" labelPosition="top" ref="myForm"></pk-form>
      </div>
    </pk-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps, onMounted, defineEmits } from 'vue'
import pkDialog from '@/components/pkui/pk-dialog/pk-dialog.vue'
import pkForm from '@/components/pkui/pk-form/pk-form.vue'
import { dutiesCreate, dutiesUpdate } from '@/api/api'
const emit = defineEmits(['confirm', 'onClose'])
const title = ref('')
const loading = ref(false)
const props = defineProps({
  curData: {
    type: Object,
    default: () => {}
  }
})
const myForm = ref()
const formConfig = ref([
  {
    label: '级别名称',
    type: 'input',
    prop: 'name'
  },
  {
    label: '权重',
    type: 'input',
    prop: 'ratio'
  }
])

const onClose = () => {
  emit('onClose')
}

const postAdd = (data) => {
  loading.value = true
  dutiesCreate({
    ...data
  }).then(res => {
    loading.value = false
    emit('confirm')
  }).catch(err => {
    loading.value = false
  })
}

const postEdit = (data) => {
  loading.value = true
  let params = {
    ...data,
    id: props.curData.id
  }
  dutiesUpdate(params).then(res => {
    emit('confirm')
    loading.value = false
  }).catch(err => {
    loading.value = false
  })
}


const confirm = () => {
  myForm.value.submitForm().then(res => {
    if (props.curData?.id) {
      postEdit(res)
    } else {
      postAdd(res)
    }
  })
}

const initStart = () => {
  if (props.curData?.id) {
    title.value = '编辑账号'
    myForm.value.setFormProp('name', props.curData.name)
    myForm.value.setFormProp('ratio', props.curData.ratio)
  } else {
    title.value = '添加账号'
  }
}

onMounted(() => {
  setTimeout(() => {
    initStart()
  }, 100)
})
</script>

<style lang="scss" scoped>

</style>